﻿using BlogModels;
using BlogWeb.Filters;
using BlogWeb.Models;
using bTools;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace BlogWeb.Controllers
{
    public class AdminController : Controller
    {
        private BlogsDbContext db = new BlogsDbContext();

        /// <summary>
        /// 登录的Action方法 ，访问方式GET: Admin
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 登录的Action方法 ，访问方式POST: Admin
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login([Bind(Include = "Acc,Pwd,ChkCode")]AdLogin lg)
        {
            //验证码核对
            if (lg.ChkCode != Session["ValidateCode"].ToString())
            {
                ModelState.AddModelError("", "验证码不正确.");
                return View(lg);
            }
            string pwd = MyMd5.MD5Encrypt32(lg.Pwd);//加密密码
            var admin = db.Admins.Where(a => a.Acc == lg.Acc && a.Pwd == pwd).FirstOrDefault();//查询用户名和密码是否正确

            if (admin != null)
            {
                Session["Admin"] = lg.Acc;//用户名存放到Session全局对象内，（全局是用户级别的全局）

                return RedirectToAction("Index");
            }
            else
            {
                ModelState.AddModelError("", "用户名或密码不正确.");
                return View(lg);
            }
           
        }
        /// <summary>
        /// 注销登录
        /// </summary>
        /// <returns></returns>
        [Admin]
        public ActionResult LoginOut()
        {
            Session["Admin"] = null;
            ClearClientPageCache();
            return RedirectToAction("Login"); ;
        }
        /// <summary>
        /// 修改密码 GET
        /// </summary>
        /// <returns></returns>
        [Admin]
        public ActionResult Chgpwd()
        {
            return View();
        }
        /// <summary>
        /// 修改密码 POST
        /// </summary>
        /// <returns></returns>
        [Admin]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Chgpwd([Bind(Include = "OldPwd,NewPwd,ChkPwd")]ChangePwdView chgpwd)
        {
            if (ModelState.IsValid)
            {
                //获取admin登录后保存的Session值
                string acc = Session["Admin"].ToString();
                
                //从数据库中获取admin对象
                Admin admin = db.Admins.Where(a => a.Acc == acc).FirstOrDefault();
                //验证原始密码：1、加密输入的原始密码
                string oldpwd = MyMd5.MD5Encrypt32(chgpwd.OldPwd);
                if (admin.Pwd == oldpwd)//2、如果原始密码正确
                {
                    //加密新密码并给admin对象的Pwd（密码）属性赋值
                    admin.Pwd = MyMd5.MD5Encrypt32(chgpwd.NewPwd);
                    //设置数据库中的admin对象为可修改模式
                    db.Entry(admin).State = System.Data.Entity.EntityState.Modified;
                    //保存修改
                    await db.SaveChangesAsync();
                    Response.Write("<script>alert(\"密码修改成功！请重新登录！\");</script>");
                    Response.Write("<script>parent.location.href='LoginOut';</script>");//当前页面的父级框架页跳转到LoginOut，实现整个页面注销
                    //return RedirectToAction("LoginOut","Admin");
                }
                else
                {
                    Response.Write("<script>alert('原始密码不正确！');</script>");
                }
            }
            return View(chgpwd);
        }
        [Admin]
        public ActionResult Top()
        {
            return View();
        }
        [Admin]
        public ActionResult Left()
        {
            return View();
        }
        [Admin]
        public ActionResult Swich()
        {
            return View();
        }
        [Admin]
        public ActionResult Main()
        {
            return View();
        }
        [Admin]
        public ActionResult Bottom()
        {
            return View();
        }

        [Admin]
        public ActionResult Index()
        {          
            return View();
        }

        private void ClearClientPageCache()
        {
            //清除浏览器缓存
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.Cache.SetNoStore();

        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}